<template>
  <div class="drill">
    <!-- 国际化切换 -->
    <!-- <el-button mb-2 @click="toggleLanguage('zhCn')">中文</el-button>
    <el-button mb-2 @click="toggleLanguage('en')">English</el-button>
    <el-button mb-2 @click="toggleLanguage('ja')">日本語</el-button>
    <br /> 
   <el-config-provider :locale="locale"> 
     </el-config-provider>  -->

    <!-- 创作数据和训练 -->
    <div class="top">
      <!-- 创建数据 -->
      <div class="create">
        <el-card
          class="createCard"
          @click="toCreate()"
          @mouseover="isCreate = true"
          @mouseout="isCreate = false"
        >
          <div class="createButton">
            <div class="logo">
              <img :src="isCreate ? moxing2 : moxing" alt="" />
            </div>

            <div class="logoOUT">
              <div class="main">创建模型</div>
              <div class="round">在线填写基础信息 快速创建模型</div>

              <div class="begin">开始</div>
              <div class="logo2">
                <img :src="isCreate ? jiantou : jiantou2" alt="" />
              </div>
            </div>
            <!-- 国际化 -->
            <!-- <div class="main">{{ locale.createModel }}</div>
              <div class="round">{{ locale.fillInformation }}</div>

              <div class="begin">
                {{ locale.start }}
                 <div class="logo2">
                  <img :src="isCreate ? jiantou : jiantou2" alt="" />
                </div>
              </div> -->
          </div></el-card
        >
      </div>
    </div>

    <!-- 下边的数据集 -->
    <div
      class="down"
      v-loading="loading"
      element-loading-text="玩命删除中 请稍等..."
      :element-loading-spinner="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
    >
      <el-card class="allDataCard">
        <div class="tableTop">
          <img src="../assets/../assets/image/云数据库.svg" alt="" />
          <div class="text">已有模型列表</div>
          <div class="input">
            <el-input
              v-model="search"
              placeholder="请输入您的模型名称..."
              size="large"
              style="width: 400px"
            >
              <template #prefix>
                <img src="../assets/image/放大镜.svg" alt="" /> </template
            ></el-input>
          </div>
        </div>
        <div class="downTable">
          <div style="height: 400px; overflow: auto">
            <el-table
              :data="filterTableData"
              class-name="elTable"
              style="height: 100%"
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="100" />
              </template>
              <el-table-column
                class-name="eltableColumn"
                label="模型名称"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="模型类型"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="数据集名称类型"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="数据集描述"
                prop="container_name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="基础模型"
                prop="basics_model"
              />
              <!-- <el-table-column
                class-name="eltableColumn"
                label="镜像地址"
                prop="image_name"
              /> -->
              <el-table-column
                class-name="eltableColumn"
                label="创建时间"
                prop="creat_time"
              />
              <el-table-column
                class-name="eltableColumn"
                label="发布"
                prop="container_name"
              >
                <el-switch v-model="value1"
              /></el-table-column>

              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    round
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)"
                    >训练</el-button
                  >

                  <el-button
                    size="small"
                    round
                    @click="handleName(scope.$index, scope.row)"
                  >
                    编辑
                  </el-button>

                  <el-button
                    size="small"
                    round
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 编辑回显的弹窗 -->
          <el-dialog v-model="dialogVisible">
            <el-form :model="editingRowData">
              <el-form-item label="模型名称">
                <el-input v-model="editingRowData.container_name" />
              </el-form-item>
            </el-form>
            <div slot="footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="nameChange()">确认</el-button>
            </div>
          </el-dialog>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {
  ElCard,
  ElDialog,
  ElInput,
  ElTable,
  ElTableColumn,
  ElButton,
  ElEmpty,
  ElMessageBox,
  ElMessage,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElPagination,
  ElConfigProvider,
  ElSwitch
} from 'element-plus'
import { reactive, ref, computed, onMounted, provide, inject } from 'vue'
import { useRouter } from 'vue-router'
import {
  nameModel,
  delModel,
  listDeploy,
  beginDrill,
  stopDeploy,
  getModel
} from '../api/model.js'
import moxing2 from '../assets/image/模型2.png'
import moxing from '../assets/image/模型.png'
import jiantou2 from '../assets/image/箭头2.png'
import jiantou from '../assets/image/箭头.png'
import axios from 'axios'

// 国际化切换

// import zhCn from '../utils/lang/zhcn'
// import en from '../utils/lang/en.mjs'
// import ja from '../utils/lang/ja.mjs'
// const language = ref('zhCn')
// const translations = reactive({
//   zhCn: zhCn,
//   en: en,
//   ja: ja
// })

// const locale = computed(() => translations[language.value])

// const toggleLanguage = lang => {
//   language.value = lang
//   console.log(locale.value) // 输出切换后的语言对象，确保语言已经切换成功
// }

const loading = ref(false)
const value1 = ref(true)

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 3px; fill: rgba(0, 0, 0, 0)"/>`

const router = useRouter()

const modelList = ref(['测试环境', '开发环境'])

const form = ref({
  imgname: 'llama0.3',
  cont_name: 'langtrain',
  path_to_llama_model: 'src/openbuddy-openllama-7b-v5-fp16',
  model_type: 'llama',
  output_dir: '/output',
  output_path: '/nvme1/ningyu/lang_output',
  logs_path: '/nvme1/ningyu/langport_logs',
  finetuning_type: 'full',
  dataset_location: '/data/oaast_sft_zh',
  dataset_info: '',
  gpu_nums: '1',
  deepspeed_type: '1'
})

const isCreate = ref(false)

const search = ref('')
const editingRowData = ref({})
const dialogVisible = ref(false) // 编辑回显时的弹窗
let editIndex = -1 // 表示没有编辑的行
const tableData = reactive([
  {
    creat_time: '2023-05-03',
    container_name: 'Tom',
    image_name: 'https://mirrors.aliyun.com/',
    basics_model: 'langport'
  },
  {
    creat_time: '2023-05-02',
    container_name: 'John',
    image_name: 'http://mirrors.163.com/',
    basics_model: 'langport'
  },
  {
    creat_time: '2023-05-04',
    container_name: 'Morgan',
    image_name: 'https://mirrors.hust.edu.cn/',
    basics_model: 'langport'
  },
  {
    creat_time: '2023-05-01',
    container_name: 'Jessy',
    image_name: 'https://npm.taobao.org/',
    basics_model: 'langport'
  }
])

// 训练按钮
const handleEdit = () => {
  router.push('./model')
}
// 点击编辑
const handleName = (index, row) => {
  editIndex = index
  editingRowData.value = { ...row }
  dialogVisible.value = true
}
// 编辑回显名字的确认
const nameChange = () => {
  // 判断是否有编辑的行
  if (editIndex !== -1) {
    tableData.splice(editIndex, 1, { ...editingRowData })
    dialogVisible.value = false
    // tableData.value = editingRowData.value  直接赋值会失败,因为直接赋值只是赋值,而这里需要一个对象
    tableData[editIndex] = Object.assign({}, editingRowData.value)

    ElMessage({
      type: 'success',
      message: '修改成功'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '修改失败!'
    })
  }
}

// 从后台拿现有模型列表
async function fetchData () {
  try {
    await listDeploy().then(res => {
      console.log('容器列表的res', res)
      tableData.length = 0 // 清空tableData数组
      tableData.push(...res.data) // 将返回的数据添加到tableData数组中

      const styleOptions = {
        year: 'numeric',
        month: '2-digit', // 使用两位数字格式，例如：'01'
        day: '2-digit', // 使用两位数字格式，例如：'01'
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }

      const dateRegex =
        /^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})\.\d+Z$/

      tableData.forEach(item => {
        const matches = dateRegex.exec(item.creat_time)
        if (matches) {
          const [, year, month, day, hour, minute, second] = matches
          item.creat_time = new Date(
            Date.UTC(
              Number(year),
              Number(month) - 1,
              Number(day),
              Number(hour),
              Number(minute),
              Number(second)
            )
          )
            .toLocaleString(undefined, styleOptions)
            .replace(/\//g, '-')
        }
      })

      console.log('tableData', tableData)
    })
  } catch (error) {
    console.error('从后台拿现有模型列表失败', error)
  }
}

const toCreate = () => {
  router.push('./create')
}

// 搜索功能
const filterTableData = computed(function () {
  return tableData.filter(function (data) {
    return (
      !search.value ||
      data.container_name.toLowerCase().includes(search.value.toLowerCase())
    )
  })
})

// 删除按钮
const handleDelete = async (index, row) => {
  ElMessageBox.confirm(`是否删除名称为 ${row.container_name} 数据 ?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        await stopDeploy({ container_name: row.container_name })
        await delModel({
          container_name: row.container_name
        })

        tableData.splice(index, 1)
        loading.value = false

        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      } catch (error) {
        console.error('Failed to delete data:', error)
        ElMessage({
          type: 'error',
          message: '删除失败'
        })
      }
    })
    .catch(() => {})
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.drill {
  display: flex;
  margin: 0 auto;
  flex-direction: column;
  .top {
    padding: 20px;
    display: flex;
    justify-content: center;
    width: 100%;
    :deep(.createCard) {
      height: 250px;
    }
    .create {
      padding: 20px;

      ::v-deep(.el-card__body) {
        width: 1000px;
      }
      .createButton {
        display: flex;
        .logo {
          width: 20%;
          padding-left: 100px;

          img {
            width: 80px;
            height: 80px;
          }
        }

        .logoOUT {
          width: 66%;
          .logo2 {
            img {
              width: 80px;
              height: 80px;
            }
          }
          .main {
            font-size: 26px;
            font-weight: bold;
            margin-bottom: 15px;
          }
          .round {
            font-size: 20px;
            margin-bottom: 15px;
            color: #ccc;
          }

          .begin {
            font-size: 26px;
            font-weight: bold;
            margin-bottom: 30px;
          }
        }
      }
    }

    .create :hover {
      cursor: pointer;
      background: #91d5ff;
      .main {
        color: #fff;
      }
      .begin {
        color: #fff;
      }
      .round {
        color: #ffffffe2;
      }
    }
  }

  .down {
    padding: 0 35px 0px 35px;

    .tableTop {
      font-weight: bold;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 40px;
      .input {
        margin: 10px 0 0 50px;
        img {
          width: 21px;
          height: 21px;
        }
      }
      img {
        width: 70px;
        height: 70px;
      }
      .text {
        font-size: 22px;
        font-weight: bold;
        margin: 10px 0 0 50px;
      }
    }
    .downTable {
      height: 500px;
      width: 100%;
      position: relative;
      img {
        width: 20px;
        height: 20px;
      }
      .elTable {
        position: absolute;
        top: 10%;
        :deep(.eltableColumn) {
          color: black;
        }
      }
    }
  }

  :deep(.allDataCard) {
    width: 100%;
    height: 520px;
  }

  :deep(.el-popup-parent--hidden) {
    width: 100%;
  }
}


</style>
